package com.glinsoft.ticktak.util;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class Redissor {


    @Autowired
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 当前保存的所有键
     *
     * @param keys
     * @return
     */
    public Set<String> keys(String keys){
        preStub();
        try{
            return redisTemplate.keys(keys);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 键过期
     *
     * @param key
     * @param time 单位：秒
     * @return
     */
    public boolean expire(String key,long time){
        preStub();
        try{
            if(time < 1L){
                time = 1L;
            }
            redisTemplate.expire(key,time, TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 获取过期时间，单位：秒
     *
     * @param key
     * @return
     */
    public long getExpire(String key){
        preStub();
        return redisTemplate.getExpire(key,TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false 不存在
     */
    public boolean hasKey(String key){
        preStub();
        try{
            return redisTemplate.hasKey(key);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除缓存
     *
     * @param key
     */
    public void del(String... key){
        preStub();
        if(key != null && key.length > 0){
            if(key.length == 1){
                redisTemplate.delete(key[0]);
            }else{
                redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
            }
        }
    }


    /**
     * 普通缓存获取
     *
     * @param key
     * @return
     */
    public Object get(String key){
        preStub();
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(String key,Object value){
        preStub();
        try{
            redisTemplate.opsForValue().set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 普通缓存放入并设置时间
     *
     * @param key
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean set(String key,Object value,long time){
        preStub();
        try{
            if(time > 0){
                redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            }else{
                set(key,value);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 递增
     * @param key
     * @param delta
     * @return
     */
    public long incr(String key,long delta){
        preStub();
        if(delta<0){
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key,delta);
    }

    /**
     * 递减
     * @param key
     * @param delta
     * @return
     */
    public long decr(String key,long delta){
        preStub();
        if(delta<0){
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key,-delta);
    }

    /**
     * HashGet
     * @param key
     * @param item
     * @return
     */
    public Object hget(String key,String item){
        preStub();
        return redisTemplate.opsForHash().get(key,item);
    }

    /**
     * 获取key对应的所有键值
     *
     * @param key
     * @return
     */
    public Map<Object,Object> hmget(String key){
        preStub();
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key
     * @param map
     * @return
     */
    public boolean hmset(String key,Map<String,Object> map){
        preStub();
        try{
            redisTemplate.opsForHash().putAll(key,map);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * HashSet并设置过期时间
     *
     * @param key
     * @param map
     * @param time 单位：秒
     * @return
     */
    public boolean hmset(String key,Map<String,Object> map,long time){
        preStub();
        try{
            redisTemplate.opsForHash().putAll(key,map);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张Hash表插入数据，如果不存在将创建
     *
     * @param key
     * @param item
     * @param value
     * @return
     */
    public boolean hset(String key,String item,Object value){
        preStub();
        try{
            redisTemplate.opsForHash().put(key,item,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 向一张hash表放入数据，如果不存在将创建
     *
     * @param key
     * @param item
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean hset(String key,String item,Object value,long time){
        preStub();
        try{
            redisTemplate.opsForHash().put(key,item,value);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 删除hash表中的值
     * @param key
     * @param item
     */
    public void hdel(String key,Object... item){
        preStub();
        redisTemplate.opsForHash().delete(key,item);
    }


    /**
     * 判断hash表中是否有该项的值
     * @param key
     * @param item
     * @return
     */
    public boolean hHasKey(String key,String item){
        preStub();
        return redisTemplate.opsForHash().hasKey(key,item);
    }


    /**
     * hash递增
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hincr(String key,String item,double by){
        preStub();
        return redisTemplate.opsForHash().increment(key,item,by);
    }

    /**
     * hash递减
     * @param key
     * @param item
     * @param by
     * @return
     */
    public double hdecr(String key,String item,double by){
        preStub();
        return redisTemplate.opsForHash().increment(key,item,-by);
    }


    /**
     * 根据key获取set中的所有值
     * @param key
     * @return
     */
    public Set<Object> sGet(String key){
        preStub();
        try{
            return redisTemplate.opsForSet().members(key);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从hash表中查询是否存在
     * @param key
     * @param value
     * @return
     */
    public boolean sHasKey(String key,Object value){
        preStub();
        try{
            return redisTemplate.opsForSet().isMember(key,value);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将数据放入set缓存
     *
     * @param key
     * @param values
     * @return
     */
    public long sSet(String key,Object... values){
        preStub();
        try{
            return redisTemplate.opsForSet().add(key,values);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key
     * @param time 单位：秒
     * @param values
     * @return
     */
    public long sSetAndTime(String key,long time,Object... values){
        preStub();
        try{
            Long count = redisTemplate.opsForSet().add(key,values);
            if(time > 0){
                expire(key,time);
            }
            return count;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取set缓存的长度
     * @param key
     * @return
     */
    public long sGetSetSize(String key){
        preStub();
        try{
            return redisTemplate.opsForSet().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的值
     *
     * @param key
     * @param values
     * @return
     */
    public long setRemove(String key,Object... values){
        preStub();
        try{
            return redisTemplate.opsForSet().remove(key,values);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 获取list中的值
     *
     * @param key
     * @param start
     * @param end
     * @return
     */
    public List<Object> lGet(String key, long start, long end){
        preStub();
        try{
            return redisTemplate.opsForList().range(key,start,end);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key
     * @return
     */
    public long lGetListSize(String key){
        preStub();
        try{
            return redisTemplate.opsForList().size(key);
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 根据索引查询list中的值
     *
     * @param key
     * @param index
     * @return
     */
    public Object lGetByIndex(String key,long index){
        preStub();
        try{
            return redisTemplate.opsForList().index(key,index);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key,Object value){
        preStub();
        try{
            redisTemplate.opsForList().rightPush(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean lSet(String key,Object value,long time){
        preStub();
        try{
            redisTemplate.opsForList().rightPush(key,value);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key,List<Object> value){
        preStub();
        try{
            redisTemplate.opsForList().rightPushAll(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean lSet(String key,List<Object> value,long time){
        preStub();
        try{
            redisTemplate.opsForList().rightPushAll(key,value);
            if(time > 0){
                expire(key,time);
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 更新list中某个索引的值
     *
     * @param key
     * @param index
     * @param value
     * @return
     */
    public boolean lUpdateIndex(String key,long index,Object value){
        preStub();
        try{
            redisTemplate.opsForList().set(key,index,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 移除N个值为value的值
     *
     * @param key
     * @param count
     * @param value
     * @return
     */
    public long lRemove(String key,long count,Object value){
        preStub();
        try{
            Long remove = redisTemplate.opsForList().remove(key,count,value);
            return remove;
        }catch (Exception e){
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * SetNX
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setIfAbsent(final String key, final Serializable value){
        preStub();
        Boolean b = redisTemplate.execute(new RedisCallback<Boolean>() {

            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                Object obj = redisConnection.execute("setnx", keySerializer.serialize(key), valueSerializer.serialize(value));

                return obj.toString().equals("1");
            }
        });

        return b;
    }

    /**
     * SetNX
     *
     * @param key
     * @param value
     * @param time 单位：秒
     * @return
     */
    public boolean setIfAbsent(final String key, final Serializable value,final long time){
        preStub();
        Boolean b = redisTemplate.execute(new RedisCallback<Boolean>() {

            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer keySerializer = redisTemplate.getKeySerializer();
                RedisSerializer valueSerializer = redisTemplate.getValueSerializer();
                Object obj = redisConnection.execute("setnx", keySerializer.serialize(key), valueSerializer.serialize(value));

                boolean rst =  obj.toString().equals("1");
                if(rst){
                    expire(key,time);
                }
                return rst;
            }
        });

        return b;
    }


    private void preStub(){
        Assert.notNull(redisTemplate,"此SpringBoot应用未启用Redis配置");
    }


}
